from datetime import datetime, date
from pymongo import MongoClient
import sys
from pathlib import Path

# 加入项目根路径
sys.path.append(str(Path(__file__).parent.parent))

# 模块导入（保持绝对导入更稳定）
from dynamic_pricing.pricing_data import compute_pricing_features
from utils.config_loader import load_settings

# 加载配置
settings = load_settings()
MONGO_URI = settings['mongodb']['uri']
MONGO_DB = settings['mongodb']['database']

def save_pricing_results(df_result, target_date: date):
    """
    将 new_price 和 trigger_recommendation 写回 MongoDB，
    同时追加到 price_history。
    """
    client = MongoClient(MONGO_URI)
    db = client[MONGO_DB]
    
    # 转换为 datetime 类型（MongoDB 不支持 date）
    ts = datetime.combine(target_date, datetime.min.time())

    for _, row in df_result.iterrows():
        pid = row['product_id']
        new_price = round(row['new_price'], 2)
        trigger = bool(row['trigger_recommendation'])

        found = False
        for coll_name in db.list_collection_names():
            coll = db[coll_name]
            res = coll.update_one(
                {"_id": pid},
                {
                    "$push": {
                        "price_history": {
                            "date": ts,
                            "price": new_price
                        }
                    },
                    "$set": {
                        "latest_price": new_price,
                        "price_updated_at": ts,
                        "trigger_recommendation": trigger
                    }
                }
            )
            if res.matched_count:
                found = True
                break
        
        if not found:
            print(f"⚠️ 未找到商品 {pid} 所在集合，未写入。")

    client.close()


def run_pricing(target_date: date = None):
    """
    主运行函数：执行定价流程，返回触发推荐更新的商品 ID 列表
    """
    if target_date is None:
        target_date = date.today()

    print(f"🚀 执行定价任务，目标日期：{target_date}")

    # 1. 计算新价格
    df_feat = compute_pricing_features(target_date)
    if df_feat.empty:
        print("⚠️ 没有可定价的商品，退出。")
        return []

    # 2. 写入数据库
    save_pricing_results(df_feat, target_date)
    print(f"✅ 写入 {len(df_feat)} 条定价记录。")

    # 3. 提取触发推荐商品
    triggered = df_feat[df_feat['trigger_recommendation']]['product_id'].tolist()
    if triggered:
        print(f"🔔 触发推荐更新的商品：{triggered}")
    else:
        print("🔕 没有商品触发推荐更新。")

    return triggered


if __name__ == "__main__":
    # 本地测试
    triggered = run_pricing(date(2025, 3, 25))
    print("✅ 执行完毕。")
